package com.ayi.utils;

import com.ayi.bean.Book;
import com.ayi.dao.bookdao.QueryBook;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * @author Ayingzz
 * @create 2021/11/29 16:17
 */
public class CartBuilder {

    /**
     * 订单构建
     * @param rs
     * @return
     */
    public List<Book> cartBuild(ResultSet rs) {
        try {
            if (rs.next()) {
                String currentIdStr = rs.getString("cartList");
                Set<Integer> idGroup = new HashSet<>();
                Map<Integer, Integer> numGroup = new HashMap<>();
                if ("".equals(currentIdStr)) {
                    return null;
                } else {
                    String[] currentIdGroup = currentIdStr.split("#");
                    for (int i = 0, n = currentIdGroup.length; i < n; i++) {
                        int eqIndex = currentIdGroup[i].indexOf('=');
                        int groupLength = currentIdGroup[i].length();
                        Integer id = Integer.valueOf(currentIdGroup[i].substring(0, eqIndex));
                        Integer num = Integer.valueOf(currentIdGroup[i].substring(eqIndex + 1, groupLength));
                        idGroup.add(id);
                        numGroup.put(id, num);
                    }
                    return new QueryBook().queryBooksByIdGroup(idGroup, numGroup);
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

}
